﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace SocketRecv
{
    public class StateObject
    {
        public Socket ClientSock { get; set; }
        public byte[] Data { get; set; }
    }

    class Program
    {
        private static Socket ConnectSocket()
        {
            Socket s = null;
            IPEndPoint hostEntry = null;

            hostEntry = new IPEndPoint(IPAddress.Any, 5657);
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            s.Bind(hostEntry);

            return s;
        }

        public static void Main(string[] args)
        {
            Socket s = ConnectSocket();
            s.Listen(100);

            int i = 0;

            while (true)
            {
                Socket clientSock = s.Accept();
                Console.WriteLine("Recv File");

                long len = 367839232;
                byte[] clientData = new byte[len];

                StateObject so = new StateObject();
                so.ClientSock = clientSock;
                so.Data = clientData;


                SocketError se;
                AsyncCallback ac = new AsyncCallback(Read_Callback);

                IAsyncResult receivedBytesLen = clientSock.BeginReceive(so.Data, 0, so.Data.Length, SocketFlags.None, out se, ac, so);

                Console.WriteLine("End Recv File");
            }

            Console.Read();
        }

        private static int m_i = 0;

        public static void Read_Callback(IAsyncResult ar)
        {
            StateObject so = ar.AsyncState as StateObject;

            int read = so.ClientSock.EndReceive(ar);

            BinaryWriter bWrite = new BinaryWriter(File.Open(string.Format("b{0}.avi", m_i), FileMode.Append)); ;
            bWrite.Write(so.Data, 0, so.Data.Length);

            bWrite.Close();

            so.ClientSock.Close();
            m_i++;
        }
    }
}
